package com.eightbears.beboy.ui.user.fragment;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopInfoAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.AMapUtil;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.DensityUtil;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.builder.GetBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.AutoSortPopup;
import com.eightbears.beboy.base.view.popupwindow.FindClassifyPopup;
import com.eightbears.beboy.base.view.popupwindow.LocationSortPopup;
import com.eightbears.beboy.entity.ClassifyEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.ShopListEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.SearchShopActivity;
import com.eightbears.beboy.ui.user.activity.ShopDetailActivity;
import com.eightbears.greendao.District;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.support.design.widget.BottomSheetBehavior.STATE_COLLAPSED;
import static android.support.design.widget.BottomSheetBehavior.STATE_HIDDEN;
import static com.eightbears.beboy.adapter.ShopInfoAdapter.STATUS_RIORITY_RECOMMEND;
import static com.eightbears.beboy.adapter.ShopInfoAdapter.STATUS_RIORITY_SIGN;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT_VALUE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.EVENT_CHANGE_CITY;

public class FindFragment extends BaseFragment implements LocationSource,
        AMapLocationListener, AMap.OnCameraChangeListener, AMap.OnMarkerClickListener
        , AMap.OnMapClickListener, AMap.OnInfoWindowClickListener,
        DistrictSearch.OnDistrictSearchListener, BaseQuickAdapter.RequestLoadMoreListener {
    private static String PARAMS_FIND_PAGE_SIZE = "99";
    public static String PARAMS_SHOP_ID = "shopId";

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    @BindView(R.id.tmv_amap)
    TextureMapView mapView;
    @BindView(R.id.iv_find_right)
    ImageView iv_find_right;
    @BindView(R.id.view_top)
    View view_top;
    @BindView(R.id.tv_shop_name)
    TextView tv_shop_name;
    @BindView(R.id.tv_recommend)
    TextView tv_recommend;
    @BindView(R.id.icon_hongbao)
    ImageView icon_hongbao;
    @BindView(R.id.iv_shop_image)
    ImageView iv_shop_image;
    @BindView(R.id.tv_shop_sale)
    TextView tv_shop_sale;
    @BindView(R.id.tv_shop_comment)
    TextView tv_shop_comment;
    @BindView(R.id.tv_shop_address)
    TextView tv_shop_address;
    @BindView(R.id.tv_shop_distance)
    TextView tv_shop_distance;
    @BindView(R.id.rb_start)
    RatingBar rb_start;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.bottom_sheet)
    View bottomSheet;
    @BindView(R.id.cv_search_shop)
    CardView cv_search_shop;
    @BindView(R.id.rl_search_title)
    RelativeLayout rl_search_title;
    @BindView(R.id.view_search_menu)
    View view_search_menu;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.ll_location)
    LinearLayout ll_location;
    @BindView(R.id.ll_rank)
    LinearLayout ll_rank;
    @BindView(R.id.tv_classify)
    TextView tv_classify;
    @BindView(R.id.tv_result_sort)
    TextView tv_result_sort;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.view_find_title)
    View view_find_title;
    @BindView(R.id.tv_btn_gps)
    TextView tv_btn_gps;

    @BindView(R.id.view_bottom_info)
    RelativeLayout view_bottom_info;
    @BindView(R.id.ll_bottom_view)
    LinearLayout ll_bottom_view;

    private AMap aMap;                                      // 地图
    private OnLocationChangedListener mListener;            // 定位监听
    private AMapLocationClient mlocationClient;             // 设置
    private AMapLocationClientOption mLocationOption;       // 设置
    private BitmapDescriptor bitmapDescriptor;
    private LatLng location;
    private CameraPosition cameraPosition;
    private UiSettings mUiSettings;
    private Bitmap markTipBitmap;
    private BottomSheetBehavior behavior;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private int height;
    private int currentZoomNum = 17;
    private String[] content;
    private List<Marker> optionList;

    private String classifyId = "0", orderId = "1", distanceId = "0", shopId;

    private LocationEntity locationEntity;
    private ShopListEntity shoMapEntity;
    private ShopListEntity shopListEntity;
    private UserEntity mUserEntity;
    private ShopInfoAdapter shopInfoAdapter;
    private GetBuilder shopsBuilder;
    private GetBuilder shopsListBuilder;

    private LatLng gpsLatlng;
    private FindClassifyPopup findClassifyPopup;
    private AutoSortPopup autoSortPopup;
    private LocationSortPopup locationSortPopup;
    private DensityUtil densityUtil;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_find, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        mapView.onCreate(savedInstanceState);
        initMap();
        initView();
        initData();
        initEvent();
        return view;
    }


    @Override
    protected void initView() {
        densityUtil = new DensityUtil(getActivity());

        WindowManager wm = getActivity().getWindowManager();
        height = wm.getDefaultDisplay().getHeight();
        ViewGroup.LayoutParams linearParams = bottomSheet.getLayoutParams();
        if (CommonUtils.checkDeviceHasNavigationBar(getContext())) {
            linearParams.height = height - DensityUtil.dip2px(93f) - densityUtil.getVirtualBarHeigh();
        } else {
            linearParams.height = height - DensityUtil.dip2px(141f) - densityUtil.getStatusBarHeight() - densityUtil.getVirtualBarHeigh();
        }
        bottomSheet.setLayoutParams(linearParams);
        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setPeekHeight(height / 2);
        initAdapter();
        initPopup();
    }

    @Override
    protected void initData() {
        mUserEntity = SPUtil.getUser();
    }

    @Override
    protected void initEvent() {
        initBottomSheetEvent();
        shopInfoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ShopListEntity.DataBean.ListBean listBean = (ShopListEntity.DataBean.ListBean) adapter.getData().get(position);
                if (view.getId() == R.id.shop_info_root) {
                    startLocalActivity(ShopDetailActivity.class, PARAMS_SHOP_ID, listBean.getShop_id());
                }
            }
        });
        initLeftEvent();

        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                if (behavior.getState() == STATE_COLLAPSED) {
                    behavior.setState(STATE_HIDDEN);
                }
            }
        });
    }

    private void initBottomSheetEvent() {

        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @BottomSheetBehavior.State int newState) {
                String state = "null";
                switch (newState) {
                    case 1:
                        state = "STATE_DRAGGING";
                        break;
                    case 2:
                        state = "STATE_SETTLING";
                        break;
                    case 3:
                        state = "STATE_EXPANDED";
                        break;
                    case 4:
                        state = "STATE_COLLAPSED";
                        break;
                    case 5:
                        state = "STATE_HIDDEN";
                        break;
                }
                Log.d("MainActivity", "newState:" + state);
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                showHindSearchBar(slideOffset);
                showHindBottomBottom(slideOffset);
                showSearchMenu(slideOffset);
            }
        });
    }

    @OnClick(R.id.tv_btn_gps)
    void goGps() {
        CommonUtils.showMapSelView(getActivity(), gpsLatlng);
    }

    private void showSearchMenu(float slideOffset) {
        if (slideOffset == 1) {
            view_search_menu.setVisibility(View.VISIBLE);
            rl_search_title.setVisibility(View.VISIBLE);
        } else {
            view_search_menu.setVisibility(View.GONE);
            rl_search_title.setVisibility(View.GONE);
        }
    }

    private void showHindSearchBar(float slideOffset) {
        if (slideOffset > 0) {
            if (cv_search_shop.getVisibility() == View.VISIBLE) {
                Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_hind);
                anim.setFillAfter(true);
                cv_search_shop.startAnimation(anim);
                cv_search_shop.setVisibility(View.GONE);
            }
        } else {
            if (cv_search_shop.getVisibility() == View.GONE) {
                Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_show);
                anim.setFillAfter(true);
                cv_search_shop.startAnimation(anim);
                cv_search_shop.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showHindBottomBottom(float slideOffset) {
        if (slideOffset == -1) {
            hideBottomInfo();
        } else {
            hideBottomView();
        }
    }

    private void initPopup() {
        findClassifyPopup = new FindClassifyPopup(getActivity());
        autoSortPopup = new AutoSortPopup(getActivity());
        locationSortPopup = new LocationSortPopup(getActivity());
    }

    private void initAdapter() {
        rv_list.setLayoutManager(new MyLinearLayoutManager(getActivity()));
        shopInfoAdapter = new ShopInfoAdapter();
        shopInfoAdapter.openLoadAnimation();
        shopInfoAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(shopInfoAdapter);
    }


    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();
            optionList = new ArrayList<>();
            aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
            setUpMap();
        }

    }

    private void setUpMap() {
        locationEntity = SPUtil.getUserLocation();
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.getUiSettings().setZoomControlsEnabled(false);
        setupLocationStyle();
    }


    @OnClick(R.id.cv_search_shop)
    void searchShop() {
        startLocalActivity(SearchShopActivity.class);
    }

    @OnClick(R.id.iv_location)
    void moveLocation() {
        locationReturn();
    }

    @OnClick(R.id.iv_map_add)
    void addMap() {
        currentZoomNum += 1;
        if (currentZoomNum >= 19)
            currentZoomNum = 19;
        if (currentZoomNum < 19)
            aMap.animateCamera(CameraUpdateFactory.zoomTo(++currentZoomNum));
    }

    @OnClick(R.id.iv_map_sub)
    void subMap() {
        currentZoomNum -= 1;
        if (currentZoomNum <= 3)
            currentZoomNum = 3;
        if (currentZoomNum > 3)
            aMap.animateCamera(CameraUpdateFactory.zoomTo(--currentZoomNum));
    }

    @OnClick(R.id.ll_bottom_view)
    void shopList() {
        behavior.setState(STATE_COLLAPSED);
        hideBottomView();
        locationReturn();
    }

    @OnClick(R.id.rl_search_title)
    void searchTitle() {
        startLocalActivity(SearchShopActivity.class);
    }

    @OnClick(R.id.rl_bottom_shop)
    void openShop() {
        startLocalActivity(ShopDetailActivity.class, PARAMS_SHOP_ID, shopId);
    }

    /**
     * 获取商铺信息
     */
    private void getShopInfo() {

        shopsBuilder = new GetBuilder();
        shopsBuilder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        shopsBuilder.addHeader(KEY_HTTP_HEADER_ACCEPT, KEY_HTTP_HEADER_ACCEPT_VALUE);
        shopsBuilder.url(URL_SHOPS_LIST);
        shopsBuilder.addParams("page", "1");
        shopsBuilder.addParams("size", PARAMS_FIND_PAGE_SIZE);
        shopsBuilder.addParams("user_lat", locationEntity.getLatitude());
        shopsBuilder.addParams("user_lng", locationEntity.getLongitude());
        shopsBuilder.addParams("order", "1");
        shopsBuilder.addParams("lat", locationEntity.getScreenLat());
        shopsBuilder.addParams("lng", locationEntity.getScreenLon());
        shopsBuilder.addParams("lng_radius", locationEntity.getWidthRadius());
        shopsBuilder.addParams("lat_radius", locationEntity.getHeightRadius());
        shopsBuilder.addParams("user_city_id", locationEntity.getHomeCityId());
        shopsBuilder.addParams("distance", "0");
        if (!TextUtils.isEmpty(classifyId)) {
            shopsBuilder.addParams("type", classifyId);
        }
        if (!locationEntity.getHomeCityId().equals(locationEntity.getCityId())) {
            shopsBuilder.addParams("city_id", locationEntity.getCityId());
        } else if (iv_find_right.isSelected()) {
            shopsBuilder.addParams("city_id", locationEntity.getCityId());
        }

        shopsBuilder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                shoMapEntity = GsonUtil.fromJson(response, ShopListEntity.class);
                if (shoMapEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    addLocalMarker();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }


    /**
     * 获取商铺信息
     */
    private void getShopListInfo() {

        shopsListBuilder = new GetBuilder();
        shopsListBuilder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        shopsListBuilder.addHeader(KEY_HTTP_HEADER_ACCEPT, KEY_HTTP_HEADER_ACCEPT_VALUE);
        shopsListBuilder.url(URL_SHOPS_LIST);
        shopsListBuilder.addParams("page", String.valueOf(page));
        shopsListBuilder.addParams("size", PARAMS_PAGE_SIZE);
        shopsListBuilder.addParams("user_lat", locationEntity.getLatitude());
        shopsListBuilder.addParams("user_lng", locationEntity.getLongitude());
        shopsListBuilder.addParams("order", orderId);
        shopsListBuilder.addParams("lat", locationEntity.getScreenLat());
        shopsListBuilder.addParams("lng", locationEntity.getScreenLon());
        shopsListBuilder.addParams("user_city_id", locationEntity.getHomeCityId());
        shopsListBuilder.addParams("city_id", locationEntity.getCityId());

        if (!TextUtils.isEmpty(classifyId)) {
            shopsListBuilder.addParams("type", classifyId);
        }
        if (Double.valueOf(distanceId) > 0) {
            shopsListBuilder.addParams("distance", distanceId);
        } else {
            shopsListBuilder.addParams("distance", "1");
        }

        shopsListBuilder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                shopListEntity = GsonUtil.fromJson(response, ShopListEntity.class);
                if (shopListEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    isEnd = shopListEntity.getData().isIs_end();
                    shopInfoAdapter.addData(shopListEntity.getData().getList());
                    shopInfoAdapter.loadMoreComplete();

                }
            }

            @Override
            public void onError(Call call, Exception e) {
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    private void initLeftEvent() {
        // 点击全部
        ll_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFindClassify();
            }
        });

        ll_rank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAutoSort();
            }
        });

        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openLocationSort();
            }
        });
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                location = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                initUserLocalInfo();
                initScreenPosition();
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            } else {
                ShowToast.showShortToast(getString(R.string.text_location_error));
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(6000 * 10 * 5);
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }
    }

    private void setupLocationStyle() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        myLocationStyle.strokeColor(STROKE_COLOR);
        myLocationStyle.strokeWidth(5);
        myLocationStyle.radiusFillColor(FILL_COLOR);
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 初始化用户坐标信息
     */
    private void initUserLocalInfo() {
        // 更新用户定位信息
        locationEntity.setLatitude(location.latitude + "");
        locationEntity.setLongitude(location.longitude + "");
        SPUtil.putUserLocation(locationEntity);
    }


    /**
     * 初始化屏幕中心坐标信息
     */
    private void initScreenPosition() {
        cameraPosition = aMap.getCameraPosition();
        locationEntity.setScreenLat(cameraPosition.target.latitude + "");
        locationEntity.setScreenLon(cameraPosition.target.longitude + "");
        SPUtil.putUserLocation(locationEntity);
    }

    private List<ShopListEntity.DataBean.ListBean> markerList;

    public void addLocalMarker() {
        markerList = shoMapEntity.getData().getList();
        for (int i = 0; i < markerList.size(); i++) {
            if (i != 99) {
                ShopListEntity.DataBean.ListBean listBean = markerList.get(i);
                bitmapDescriptor = AMapUtil.getTipByShopTip(listBean);
                if (null != bitmapDescriptor) {
                    markTipBitmap = bitmapDescriptor.getBitmap();
                    Marker marker = aMap.addMarker(new MarkerOptions()
                            .position(new LatLng(Double.parseDouble(markerList.get(i).getLatitude()), Double.parseDouble(markerList.get(i).getLongitude())))
                            .title(markerList.get(i).getTitle() + "/" + markerList.get(i).getShop_id() + "/" + (i + 1))
                            .snippet(markerList.get(i).getAddress())
                            .icon(BitmapDescriptorFactory.fromBitmap(markTipBitmap)));
                    optionList.add(marker);
                }
            }

        }
    }

    /**
     * 按分类筛选
     */
    private void openFindClassify() {
        findClassifyPopup.setOnClickItemListener(new FindClassifyPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                tv_classify.setText(classifyEntity.getClassifyName());
                findClassifyPopup.selectItem(classifyEntity);
                classifyId = classifyEntity.getId();
                shopInfoAdapter.getData().clear();
                page = 1;
                clearMaker();
                getShopInfo();
                getShopListInfo();
            }
        });
        findClassifyPopup.showDropDown(view_top);
    }

    private void openAutoSort() {
        autoSortPopup.setOnClickItemListener(new AutoSortPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                tv_result_sort.setText(classifyEntity.getClassifyName());
                autoSortPopup.selectItem(classifyEntity);
                orderId = classifyEntity.getId();
                page = 1;
                shopInfoAdapter.getData().clear();
//                clearMaker();
                getShopListInfo();
            }
        });
        autoSortPopup.showDropDown(view_top);
    }

    private void openLocationSort() {

        // 左边菜单
        locationSortPopup.setOnMenuClickListener(new LocationSortPopup.OnMenuClickListener() {
            @Override
            public void onMenuClick(ClassifyEntity menuEntity) {
                tv_location.setText(menuEntity.getClassifyName());
                locationSortPopup.selectMenu(menuEntity);
            }
        });


        // 选择距离
        locationSortPopup.setOnClickItemListener(new LocationSortPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                locationSortPopup.selectItem(classifyEntity);
                distanceId = classifyEntity.getId();
                locationSortPopup.selectDistrict(null);
                shopInfoAdapter.getData().clear();
                page = 1;
                getShopListInfo();
            }
        });

        // 选择区域
        locationSortPopup.setOnDistrictClickListener(new LocationSortPopup.OnDistrictClickListener() {
            @Override
            public void onDistrictClick(District district) {
                locationSortPopup.selectDistrict(district);
                tv_location.setText(district.getName());
                locationSortPopup.selectItem(null);

                DistrictSearch search = new DistrictSearch(getActivity());
                DistrictSearchQuery query = new DistrictSearchQuery();
                query.setKeywords(district.getName());//传入关键字
                query.setShowBoundary(true);//是否返回边界值
                search.setQuery(query);
                search.setOnDistrictSearchListener(FindFragment.this);
                search.searchDistrictAnsy();//开始搜索
            }
        });

        locationSortPopup.showDropDown(view_top);
    }

    private void changeCity() {
        locationEntity = SPUtil.getUserLocation();
        DistrictSearch search = new DistrictSearch(getActivity());
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(locationEntity.getCityName());//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(FindFragment.this);
        search.searchDistrictAnsy();//开始搜索
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        clearMaker();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

        // 可视区域
        LatLng boundsLatLng = aMap.getProjection().getVisibleRegion().latLngBounds.southwest;
        double boundsLat = boundsLatLng.latitude;
        double boundsLon = boundsLatLng.longitude;
        LatLng target = cameraPosition.target;
        locationEntity.setScreenLat(target.latitude + "");
        locationEntity.setScreenLon(target.longitude + "");
        locationEntity.setWidthRadius((boundsLon - target.longitude) + "");
        locationEntity.setHeightRadius((boundsLat - target.latitude) + "");
        SPUtil.putUserLocation(locationEntity);
        getShopInfo();
        page = 1;
        shopInfoAdapter.getData().clear();
        getShopListInfo();
    }

    private void locationReturn() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(Double.parseDouble(locationEntity.getLatitude()),
                                Double.parseDouble(locationEntity.getLongitude())), 17));
            }
        });
    }

    public void showBottomView() {
        if (null != behavior) {
            if (locationEntity.getHomeCityId().equals(locationEntity.getCityId())) {
                behavior.setState(STATE_COLLAPSED);
                hideBottomView();
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(Double.parseDouble(locationEntity.getLatitude()),
                                Double.parseDouble(locationEntity.getLongitude())), 17));
            }
            KLog.e(locationEntity.getHomeCityId() + "/" + locationEntity.getCityId());
        }

    }

    private ShopListEntity.DataBean.ListBean shopEntity;

    @Override
    public boolean onMarkerClick(Marker marker) {
        content = marker.getTitle().split("/");
        for (int i = 0; i < markerList.size(); i++) {
            if (markerList.get(i).getShop_id().equals(content[1])) {
                shopEntity = markerList.get(i);
            }
        }
        gpsLatlng = marker.getPosition();
        tv_shop_name.setText(content[2] + ". " + shopEntity.getTitle());
        String common = String.format(getActivity().getResources().getString(R.string.text_shop_common), shopEntity.getComment() + "");
        tv_shop_comment.setText(common);
        shopId = content[1];
        DecimalFormat df = new DecimalFormat("#.#");
        String distance = df.format(shopEntity.getDistance());
        if (Double.parseDouble(distance) <= Double.valueOf(0.5)) {
            tv_shop_distance.setText("<500m");
        } else if (Double.parseDouble(distance) > Double.valueOf(0.5)) {
            tv_shop_distance.setText(distance + "km");
        }
        if (shopEntity.getPriority().equals(STATUS_RIORITY_RECOMMEND)) {
            showRecommend();
        } else if (shopEntity.getPriority().equals(STATUS_RIORITY_SIGN)) {
            showSign();
        }
        if (shopEntity.getHongbao().equals("1")) {
            showHongBao();
        }

        CommonUtils.loadImageView(getActivity(), shopEntity.getCover(), R.mipmap.icon_default_shop, iv_shop_image);
        String sales = String.format(getActivity().getResources().getString(R.string.text_shop_sale), shopEntity.getSales());
        tv_shop_sale.setText(sales);
        tv_shop_address.setText(shopEntity.getAddress());
        rb_start.setRating((float) shopEntity.getScore());


        showBottomInfo();
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 17));
        return true;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        hideBottomInfo();
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        KLog.e("onInfoWindowClick");
    }


    private void clearMaker() {
        //遍历清除泡泡
        for (Marker mark : optionList) {
            mark.remove();
        }
        optionList.clear();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


//    // 功能条显示影藏动画
//    private void findTopAnim(boolean isShow) {
//        if (isShow) {
//            if (ll_find_top.getHeight() > 0)
//                return;
//            valueAnimator = ValueAnimator.ofInt(0, DensityUtil.dip2px(45));
//        } else {
//            if (ll_find_top.getHeight() == 0)
//                return;
//            valueAnimator = ValueAnimator.ofInt(DensityUtil.dip2px(45), 0);
//        }
//
//        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator valueAnimator) {
//                int h = (Integer) valueAnimator.getAnimatedValue();
//                ll_find_top.getLayoutParams().height = h;
//                ll_find_top.requestLayout();
//            }
//        });
//        valueAnimator.setDuration(200);
//        //开始动画
//        valueAnimator.start();
//    }


    @Override
    public void onDistrictSearched(DistrictResult districtResult) {

        if (null != districtResult.getDistrict() && districtResult.getDistrict().size() > 0) {
            LatLonPoint latLonPoint = districtResult.getDistrict().get(0).getCenter();
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()), 17));
            distanceId = "0";
            page = 1;
            getShopListInfo();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_CHANGE_CITY:
                changeCity();
                break;
        }
    }

    private void showRecommend() {
        tv_shop_name.setTextColor(getActivity().getResources().getColor(R.color.text_shop_recommend));
        tv_recommend.setVisibility(View.VISIBLE);
    }

    private void showSign() {
        tv_shop_name.setTextColor(getActivity().getResources().getColor(R.color.text_shop_sign));
    }

    private void showHongBao() {
        Glide.with(getActivity()).load(R.mipmap.gif_icon_honghao).asGif().into(icon_hongbao);
        icon_hongbao.setVisibility(View.VISIBLE);
    }


    private void showBottomViewBtn() {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pickerview_slide_in_bottom);
        ll_bottom_view.setAnimation(animation);
        animation.start();
        ll_bottom_view.setVisibility(View.VISIBLE);
    }

    private void hideBottomViewBtn() {
        if (ll_bottom_view.getVisibility() == View.VISIBLE) {
            Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pickerview_slide_out_bottom);
            ll_bottom_view.setAnimation(animation);
            animation.start();
            ll_bottom_view.setVisibility(View.GONE);
        }
    }

    private void hideBottomView() {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pickerview_slide_out_bottom);
        ll_bottom_view.setAnimation(animation);
        animation.start();
        ll_bottom_view.setVisibility(View.GONE);

        view_bottom_info.setAnimation(animation);
        animation.start();
        view_bottom_info.setVisibility(View.GONE);

        tv_btn_gps.setAnimation(animation);
        animation.start();
        tv_btn_gps.setVisibility(View.GONE);
    }

    private void showBottomInfo() {
        if (view_bottom_info.getVisibility() != View.VISIBLE) {
            Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pickerview_slide_in_bottom);
            view_bottom_info.setAnimation(animation);
            animation.start();
            view_bottom_info.setVisibility(View.VISIBLE);
            tv_btn_gps.setAnimation(animation);
            animation.start();
            tv_btn_gps.setVisibility(View.VISIBLE);
        }
        if (ll_bottom_view.getVisibility() != View.GONE && view_bottom_info.getVisibility() == View.VISIBLE)
            ll_bottom_view.setVisibility(View.GONE);
        else
            hideBottomViewBtn();
    }

    private void hideBottomInfo() {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.pickerview_slide_out_bottom);
        view_bottom_info.setAnimation(animation);
        animation.start();
        view_bottom_info.setVisibility(View.GONE);
        tv_btn_gps.setAnimation(animation);
        animation.start();
        tv_btn_gps.setVisibility(View.GONE);
        showBottomViewBtn();
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    shopInfoAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getShopListInfo();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        shopInfoAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}